Function name: method_exists()
Applicable versions: All versions
Usage: The method_exists() function is used to check whether an object or class has a specified method.
Syntax: bool method_exists ( mixed $object , string $method_name )
parameter:
Return value: Return true if the method exists, otherwise return false.
Example:
class MyClass { public function myMethod() { // 方法实现} } // 检查对象是否具有方法$obj = new MyClass(); if (method_exists($obj, 'myMethod')) { echo "对象具有myMethod方法"; } else { echo "对象没有myMethod方法"; } // 检查类是否具有方法if (method_exists('MyClass', 'myMethod')) { echo "类具有myMethod方法"; } else { echo "类没有myMethod方法"; }
In the example above, we first create a class called MyClass containing a method called myMethod. Then, we use the method_exists() function to check if the class has a myMethod method. In the first example, we create an object $obj of MyClass and check if the object has a myMethod method. In the second example, we directly check whether the MyClass class has a myMethod method. If the method exists, the corresponding message is output, otherwise another message is output.